package com.allen.util;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * JWT-token工具类
 **/

public class Jwtutil {

    private static long time=1000*5;            //24小时
    private static String signature="admin";           //定义token的签名

    public static String createtoken(){

        JwtBuilder jwtBuilder = Jwts.builder();         //创建JWT对象（JWT三部曲：header，payload，signature）
        String jwtToken=jwtBuilder
                //header
                .setHeaderParam("typ","JWT")       //设置JWT头部信息--token类型
                .setHeaderParam("alg","HS256")
                //playload
                .claim("username","admin")
                .claim("role","admin")
                .setSubject("JWT_test")                 //主题
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();             //拼接三部曲
        return jwtToken;
    }

    public static Boolean checkToken(String token){
        if(token==null){
            return false;
        }
        try {
            Jws<Claims> claims=Jwts.parser().setSigningKey("signature").parseClaimsJws("token");
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
